<!--
 * @Author: 余铖
 * @Date: 2020-03-30 08:35:26
 * @LastEditors: 余铖
 * @LastEditTime: 2020-04-01 11:54:15
 * @Description: tab2
 -->
<template>
	<Modal v-model="modal1" title="编辑调查对象" width="860">
		<Card v-show="isExist">
			<div>
				<RadioGroup v-model="animal">
					<Radio label="随机抽选"></Radio>
					<Radio label="规则选取"></Radio>
				</RadioGroup>
			</div>
			<div v-if="animal == '随机抽选'" style="margin-top:15px">
				随机选取 <Input type="number" v-model="rule1" placeholder="请输入值" style="width: 100px" /> 个
			</div>
			<div v-else style="margin-top:15px;display: flex;">
				<div>
					每间隔 <Input type="number" v-model="rule2" placeholder="请输入值" style="width: 100px" /> 位抽取1位
				</div>
				<div style="margin-left: 50px">
					总共需要选取的人数： <Input type="number" v-model="rule3" placeholder="请输入值" style="width: 100px" />
				</div>
			</div>
			<Button v-if="btnAccess.query" type="info" style="margin: 15px 0 0 5px" @click="initSelect">确 定</Button>
			<Button :disabled="!isSure" @click="submitRule" v-if="btnAccess.query" type="warning" style="margin: 15px 0 0 15px">提 交</Button>
		</Card>
		<Card style="margin-top:15px">
			<Button v-show="!isExist"  @click="deletes" v-if="btnAccess.query" type="error" style="margin: 5px 0 15px 5px">批量删除</Button>
			<Table border :columns="columns1" :data="tableData" ref="table" @on-select="onselect"  @on-select-all="onselectall" @on-select-all-cancel="allCancel" @on-select-cancel="onselectcancel">
                <!-- @on-select="onselect" -->
                <!-- @on-select，选中某一项触发，返回值为 selection 和 row，分别为已选项和刚选择的项。
                @on-select-all，点击全选时触发，返回值为 selection，已选项。
                @on-selection-change，只要选中项发生变化时就会触发，返回值为 selection，已选项 -->
				<template slot-scope="{ row, index }" slot="number">
					<strong>{{ index+1 }}</strong>
				</template>
			</Table>
		</Card>
		<div slot="footer">
			<!-- <Button type="error" size="large" long :loading="modal_loading" @click="del">Delete</Button> -->
		</div>
	</Modal>
</template>

<script>
var _ = require("lodash");
import { requestData } from "@/api/personal.js";

export default {
	components: {},
	data() {
		return {
            modal1: false,
            
			columns1: [
				{
					type: "selection",
					width: 60,
					align: "center"
				},
				{
					title: "编号",
					width: 150,
					slot: "number",
					key: "age"
				},
				{
					title: "调查对象",
					key: "userName"
				}
			],
            tableData: [],
            isExist: true,
            
            // 父组件 数据
            itemData: {

            },

			// 单选
            animal: "随机抽选",
            // 选中的id数组
            selectId: [],
			// 规则值
			rule1: null,
			rule2: null,
			rule3: null,

			// 菜单权限 默认配置
			btnAccess: {
				add: true,
				del: true,
				upd: true,
				query: true
			},
			// 先确认 才能提交
            isSure: false,
            rule2Clicks: true
		};
	},
	mounted() {
		let btnAccess = sessionStorage.getItem("btnaccess");
        this.globalFunction(btnAccess);
        
        this.$nextTick(function () {
            document.getElementsByClassName('ivu-table-overflowX')[0].style.cssText="overflow-x: hidden !important";
            document.getElementsByClassName('ivu-modal-footer')[0].style.cssText="display: none";
        })
	},
	methods: {
		initData() {
			requestData({
				formData: { inqObjFilter: this.itemData },
				url: "/exam/User/inquireInfo"
			})
            .then(result => {
                if (result.data.code === "200") {
                    // console.log(result, "EditObject");
                    this.tableData = result.data.results.data;
                    this.isExist = result.data.results.isExist == 0 ? true : false;
                    // this.pageTotal = this.data1.length/this.pageNumber;
                } else {
                	this.$Message.error("失败");
                }
                
            })
            .catch(err => {
                console.log(err);
            });
		},
        // 执行筛选
        initSelect() {
            var obj = {};
            if(this.animal == '随机抽选') {
                obj = {
                    "rulesType": '随机规则' ,
                    "inquireSource": this.itemData.inquireSource,
                    "rulesTotal": Number(this.rule1)
                }
            } else {
                obj = {
                    "rulesType": '特定规则',
                    "rulesNum": this.rule2,
                    "inquireSource": this.itemData.inquireSource,
                    "rulesTotal": this.rule3
                }
            }

			requestData({
				formData: obj,
				url: "/app/exam/chooseObjs"
			})
            .then(result => {
                if (result.data.code === "200") {
                    console.log(result, "EditObject");
                    this.isSure = true;
                    this.tableData = result.data.results.data;
                    
                    this.actionsHock();
                    // this.pageTotal = this.data1.length/this.pageNumber;
                } else {
                	this.$Message.error("失败");
                }
                
            })
            .catch(err => {
                console.log(err);
            });
        },
        // 提交
        submitRule() {
            var data = {
                optionType: 'add',
                inqId: this.itemData.inqId,
                inqInfoId: '',
                userIdList: this.selectId
            }
            // console.log(data,'add');
			requestData({
				formData: { inqObjFilter: data },
				url: "/exam/User/inquireInfo"
			})
            .then(result => {
                if (result.data.code === "200") {
                    this.$Message.success("操作成功");
                    this.initData();
                    // console.log(result, "EditObject");
                } else {
                	this.$Message.error("失败");
                }
                
            })
            .catch(err => {
                console.log(err);
            });
        },
        // 动态勾选
        actionsHock() {
            this.selectId = [];
            this.$nextTick(() => {
                this.tableData.forEach((item,i) => {
                    // console.log(this.$refs.table.$refs.tbody.objData[i],'objData[item]');
                    this.$refs.table.$refs.tbody.objData[i]._isChecked = true;
                    this.selectId.push(this.$refs.table.$refs.tbody.objData[i].id);
                });
            })
        },
        deletes() {
            this.$Modal.confirm({
                title: "删除",
                content: "<p>是否确认删除</p>",
                loading: true,
                onOk: () => {
                    var data = {
                        optionType: 'del',
                        // inqId: this.itemData.inqId,
                        // inqInfoId: '',
                        userIdList: this.selectId
                    }
                    // console.log(data,'del');
                    requestData({
                        formData: { inqObjFilter: data },
                        url: "/exam/User/inquireInfo"
                    })
                    .then(result => {
                        if (result.data.code === "200") {
                            this.$Message.error("操作成功");
                            this.$Modal.remove();
                            this.initData();
                            // console.log(result, "EditObject");
                        } else {
                            this.$Message.error("失败");
                        }
                        
                    })
                    .catch(err => {
                        console.log(err);
                    });
                },
                onCancel: () => {
                    return;
                }
            });
        },

        
        onselect(selection,row) {
            console.log(selection, 'selection');
            this.isSure = true;
            this.selectId = [];
            selection.forEach((item) => {
                if(this.isExist) {
                    this.selectId.push(item.id);
                } else {
                    this.selectId.push(item.inqInfoId);
                }
            });
        },
        onselectcancel(selection) {
            this.isSure = true;
            if(selection.length == 0) this.isSure = false;
            this.selectId = [];
            selection.forEach((item) => {
                if(this.isExist) {
                    this.selectId.push(item.id);
                } else {
                    this.selectId.push(item.inqInfoId);
                }
            });
        },
        onselectall(selection) {
            this.isSure = true;
            this.selectId = [];
            selection.forEach((item) => {
                if(this.isExist) {
                    this.selectId.push(item.id);
                } else {
                    this.selectId.push(item.inqInfoId);
                }
            });
        },
        allCancel(selection) {
            this.isSure = false;
            this.selectId = [];
        },

        /**
         * @description: 执行筛选
         * @param {type} 
         * @return: 
         */      
		initSelect2() {
			if (
				this.rule1 > this.tableData.length &&
				this.animal == "随机抽选"
			) {
				return this.$Message.error("选取个数不能大于列表条数");
			} else if (
				(Number(this.rule2) + 1) * Number(this.rule3) > this.tableData.length &&
				this.animal != "随机抽选"
			) {
				// return this.$Message.error("此规则大于列表条数");
			} else if (!this.rule1 && this.animal == "随机抽选") {
				return this.$Message.error("请先输入数值");
			} else if (
				(!this.rule2 || !this.rule3) &&
				this.animal != "随机抽选"
			) {
				return this.$Message.error("请先输入数值");
			}

			// 重置选项框
			this.$refs.table.selectAll(false);

			// 开启提交
			this.isSure = true;
			var arr = [];
			var getArr = [];
			if (this.animal == "随机抽选") {
				getArr = this.randomNub(
					arr,
					this.rule1,
					1,
					this.tableData.length
				);
			} else {
                // 规则2
                getArr = this.setRule2( Number(this.rule2)+1, Number(this.rule3), this.rule2Clicks? 0 : Number(this.rule2));
                this.rule2Clicks = !this.rule2Clicks;
                console.log(getArr, '规则2');
			}
			//实现默认勾选
			getArr.forEach(item => {
				this.$refs.table.$refs.tbody.objData[item]._isChecked = true;
			});
			// this.selectChange();
			// console.log(getArr, '随机数');
			// console.log(this.$refs.table.$refs.tbody.objData, "初始化");
			// return;
        },
        /**
         * @description: 随机选取
         * @param aArray {Array} 空数组
         * @param len {Number} 选取的长度
         * @param min {Number} 最小值 （现在固定为1） 下面没用这个参数
         * @param max {Number} 最大值
         * @return: 筛选后的数组
         */      
		randomNub(aArray, len, min, max) {
			//5排序
			if (aArray.length >= len) {
				aArray.sort(function(a, b) {
					return a - b;
				});
				return aArray;
			}
			//1.取随机数
			var nowNub = Math.floor(Math.random() * max);
			// var nowNub = parseInt(Math.random() * (max - min - 1)) + (min - 1);
			// console.log(_.random(15, 20));  // 使用lodash 更好

			//2.判断是否重复
			for (var i = 0; i < aArray.length; i++) {
				if (nowNub === aArray[i]) {
					this.randomNub(aArray, len, min, max);
					return;
				}
			}
			//3添加到数组中
			aArray.push(nowNub);
			//4自调用 并返回数组
			this.randomNub(aArray, len, min, max);
			return aArray;
		},
        /**
         * @description: 规则选取
         * @param num1 {number} 间隔数 
         * @param num2 {number} 总共选取
         * @param initIndex {String} 总共选取
         * @param selectMore {number} 预留参数，防止后期需求变动 每次间隔选多个值
         * @return: 筛选后的数组
         */  
		setRule2(num1, num2, initIndex = 0, selectMore = 1) {
			let arr = [];
			// 总条数
			// this.tableData.length

            var i = initIndex;
			while (i <= this.tableData.length) {
                // 总共选取/间隔
                for(let x = 0;x < selectMore;x++) {
                    i = i + x;
				    arr.push(i);
                    if(arr.length >= num2) {
                        return arr;
                    }
                }
                i = i + num1;
			}
            return arr;
        }
	}
};
</script>
<style>
</style>